//
//  FMSQLiteDetailViewController.m
//  WeEsion
//
//  Created by reylen on 15/12/24.
//  Copyright © 2015年 fdauto. All rights reserved.
//

#import "FMSQLiteDetailViewController.h"
#import "FMSQLiteManager.h"
#import "FMSQLiteDetailCell.h"
#import "ProgressHUD.h"

@interface FMSQLiteDetailViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger currentPage;
    NSInteger limit;
    NSInteger columnCount;
    BOOL isEnd;
}

@property (retain, nonatomic) UITableView* tableView;
@property (retain, nonatomic) UIScrollView* scrollView;

@property (copy,nonatomic) NSArray* results;
@property (copy,nonatomic) NSArray* columnListArray;

@property (copy,nonatomic) NSString* tableName;

@property (retain, nonatomic) FMSQLiteDetailHeader* headerView;

@property (retain, nonatomic) UIBarButtonItem* nextBarButton;
@property (retain, nonatomic) UIBarButtonItem* preBarButton;


@end

@implementation FMSQLiteDetailViewController

- (instancetype)initWithStyle:(UITableViewStyle)style tableName:(NSString *) tbvName
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        self.tableName = tbvName;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.preBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRewind target:self action:@selector(prePageAction:)];
    self.nextBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFastForward target:self action:@selector(nextPageAction:)];
    self.navigationItem.rightBarButtonItems = @[self.nextBarButton,self.preBarButton];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.preBarButton.enabled = NO;
    self.nextBarButton.enabled = NO;
    
    currentPage = 1;
    limit = 20;
    
    self.title = @"Detail";
    
    [ProgressHUD show:@"加载中"];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        self.results = [self queryDataListWithPage:currentPage];
        NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES];
        if (self.results.count > 0) {
            
            NSArray*arr = [[self.results firstObject] allKeys];
            
            columnCount = [arr count];
            
            self.columnListArray = [arr sortedArrayUsingDescriptors:@[descriptor]];
            
        }
        else
        {
            self.columnListArray = [[[self sqliteManager] queryPragmaFromTable:_tableName] sortedArrayUsingDescriptors:@[descriptor]];
            columnCount = [_columnListArray count];

        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            self.nextBarButton.enabled = self.results.count == limit ? YES : NO;
            
            self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
            self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;;
            self.scrollView.contentSize = CGSizeMake(columnCount*80, 0);
            [self.view addSubview:self.scrollView];
            
            CGFloat width = [UIScreen mainScreen].bounds.size.width;
            CGFloat _tbv_width = columnCount * 80 < width ? width : columnCount*80;
            self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, _tbv_width, self.view.frame.size.height) style:UITableViewStylePlain];
            self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
            self.tableView.delegate = self;
            self.tableView.dataSource = self;
            [self.scrollView addSubview:self.tableView];
            
            [ProgressHUD dismiss];
        });
        
    });
  
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (FMSQLiteDetailHeader *)headerView {
    if (_headerView == nil) {
        
        CGFloat sWidth = [UIScreen mainScreen].bounds.size.width;
        
        CGFloat width = columnCount > 0 ? fmaxf(sWidth, columnCount * 80) : sWidth;
        _headerView = [[FMSQLiteDetailHeader alloc]initWithFrame:CGRectMake(0, 0, width, 50) titles:self.columnListArray];
    }
    
    return _headerView;
}

#pragma mark - action
- (FMSQLiteManager *) sqliteManager {
    FMSQLiteManager* sqliteManager = [FMSQLiteManager sharedManager];
    return sqliteManager;
}

- (NSArray *) queryDataListWithPage:(NSInteger) page {
    NSString* sql = [NSString stringWithFormat:@"select * from %@ limit %@ offset %@",_tableName,@(limit),@(limit*(page-1))];
    NSArray* results = [[self sqliteManager] queryWithSQL:sql];
    return results;
}

- (IBAction)prePageAction:(id)sender {
    
    currentPage --;
    self.results = [self queryDataListWithPage:currentPage];
    [self.tableView reloadData];
    
    if (currentPage == 1) {
        self.preBarButton.enabled = NO;
    }
    
    self.nextBarButton.enabled = YES;
}
- (IBAction)nextPageAction:(id)sender {
    
    currentPage ++;
    self.results = [self queryDataListWithPage:currentPage];
    [self.tableView reloadData];
    
    
    if (self.results.count == currentPage * limit) {
        self.nextBarButton.enabled = YES;
    }
    else
    {
        self.nextBarButton.enabled = NO;
        if (self.results.count == (currentPage-1)*limit) {
            currentPage --;
        }
    }
    
    self.preBarButton.enabled = YES;
    
    if (currentPage == 1) {
        self.preBarButton.enabled = NO;
    }
}
#pragma mark - TableView



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _results.count;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 50.f;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return self.headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString* iden = @"iden";
    FMSQLiteDetailCell* cell = (FMSQLiteDetailCell*)[tableView dequeueReusableCellWithIdentifier:iden];
    
    if (cell == nil) {
        cell = [[FMSQLiteDetailCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden itemCount:_columnListArray.count];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIView* line = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height - 1, cell.frame.size.width, 1)];
        line.backgroundColor = [UIColor lightGrayColor];
        line.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
        [cell.contentView addSubview:line];
    }
    
    [cell setContentInfo:[_results objectAtIndex:indexPath.row] forKeys:_columnListArray];
    
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


@end
